package com.tengju.support.infrastructure.repository.sms;

import com.tengju.support.domain.model.sms.SmsKey;
import com.tengju.support.domain.model.sms.SmsRecordRepository;
import com.tengju.support.infrastructure.persistence.redis.RedisService;
import com.tengju.support.infrastructure.persistence.redis.dataobject.RedisKeyObject;
import com.tengju.support.infrastructure.persistence.redis.dataobject.RedisKeyPrefix;
import com.tengju.support.infrastructure.shared.InfraException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 * @author chenhang
 * @Date 2021/11/15
 */
@Repository
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class SmsRecordRepositoryImpl implements SmsRecordRepository {

    private final RedisService redisService;

    private final long CACHE_TIME_DAY = 90;

    @Override
    public boolean existRecord(long idCode, SmsKey smsKey) {
        RedisKeyObject redisKey = buildKey(idCode,smsKey);
        String smsRecord = redisService.getString(redisKey);
        return !StringUtils.isEmpty(smsRecord);
    }

    @Override
    public void save(long idCode, SmsKey smsKey) {
        RedisKeyObject redisKey = buildKey(idCode,smsKey);
        redisService.setValue(redisKey,"1",CACHE_TIME_DAY, TimeUnit.DAYS);
    }

    @Override
    public void rollbackRecord(long idCode, SmsKey smsKey) {
        RedisKeyObject redisKey = buildKey(idCode,smsKey);
        redisService.delKey(redisKey);
    }

    private RedisKeyObject buildKey(long idCode, SmsKey smsKey) {
        if (smsKey == null) {
            throw new InfraException("即将晋升缓存key值生成失败，smsKey为null！");
        }
        return new RedisKeyObject(RedisKeyPrefix.UPCOMING_SMS_RECORD,smsKey.getKey() + "-" + idCode);
    }

}
